package com.tanhua.dubbo.api;

import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class CommentApiImpl implements CommentApi{
    @Autowired
    MongoTemplate mongoTemplate;

    //分页查询
    public List<Comment> findComments(String movementId, CommentType commentType, Integer page, Integer pagesize) {
        //1、构造查询条件
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(movementId)).and("commentType")
                        .is(commentType.getType()))
                .skip((page -1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        //2、查询并返回
        return mongoTemplate.find(query,Comment.class);
    }

    //发布评论，并获取评论数量
    public Integer save(Comment comment) {
        //1、查询动态
        Movement movement = mongoTemplate.findById(comment.getPublishId(), Movement.class);
        //2、向comment对象设置被评论人属性
        if(movement != null) {
            comment.setPublishUserId(movement.getUserId());
        }
        //3、保存到数据库
        mongoTemplate.save(comment);
        //4、更新动态表中的对应字段
        Query query = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if(comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount",1);
        }else if (comment.getCommentType() == CommentType.COMMENT.getType()){
            update.inc("commentCount",1);
        }else {
            update.inc("loveCount",1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true) ;//获取更新后的最新数据
        Movement modify = mongoTemplate.findAndModify(query, update, options, Movement.class);
        //5、获取最新的评论数量，并返回
        return modify.statisCount(comment.getCommentType() );
    }

    //判断comment数据是否存在
    public Boolean hasComment(String movementId, Long userId, CommentType commentType) {
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(movementId))
                .and("commentType").is(commentType.getType());
        Query query = Query.query(criteria);
        return mongoTemplate.exists(query,Comment.class); //判断数据是否存在
    }
    //删除
    public Integer delete(Comment comment) {
        //1、删除Comment表数据
        Criteria criteria = Criteria.where("userId").is(comment.getUserId())
                .and("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType());
        Query query = Query.query(criteria);
        mongoTemplate.remove(query,Comment.class);
        //2、修改动态表中的总数量
        Query movementQuery = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if(comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount",-1);
        }else if (comment.getCommentType() == CommentType.COMMENT.getType()){
            update.inc("commentCount",-1);
        }else {
            update.inc("loveCount",-1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true) ;//获取更新后的最新数据
        Movement modify = mongoTemplate.findAndModify(movementQuery, update, options, Movement.class);
        //5、获取最新的评论数量，并返回
        return modify.statisCount(comment.getCommentType() );
    }

    //根据评论id获取评论
    public Comment findById(String commentId) {
        Comment comment = mongoTemplate.findById(new ObjectId(commentId), Comment.class);
        return comment;
    }

    //更新评论点赞数
    @Override
    public Integer updateComment(Comment comment) {
        Query query = Query.query(Criteria.where("id").is(comment.getId()));
        Update update = new Update().inc("likeCount",1);

        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true) ;//获取更新后的最新数据
        Comment modify = mongoTemplate.findAndModify(query, update, options, Comment.class);
        //5、获取最新的评论数量，并返回
        if (modify!=null){
            return modify.getLikeCount();
        }else {
            return 1;
        }

    }

    @Override
    public void updateCommentByDislike(Comment comment) {
        Query query = Query.query(Criteria.where("id").is(comment.getId()));
        Update update = new Update().inc("likeCount",-1);

        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true) ;//获取更新后的最新数据
        Comment modify = mongoTemplate.findAndModify(query, update, options, Comment.class);

    }

    //分页查询评论 并返回查询条数
    @Override
    public PageResult findCommentsByPage(String movementId, CommentType commentType, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(movementId)).and("commentType")
                .is(commentType.getType()))
                .skip((page -1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        long count = mongoTemplate.count(query, Comment.class);

        return new PageResult(page,pagesize,(int)count,comments);
    }

    //保存视频评论
    @Override
    public Integer saveVideoComment(Comment comment) {
        //1、查询动态
        Video video = mongoTemplate.findById(comment.getPublishId(), Video.class);
        //2、向comment对象设置被评论人属性
        if(video != null) {
            comment.setPublishUserId(video.getUserId());
        }
        //3、保存到数据库
        mongoTemplate.save(comment);
        //4、更新动态表中的对应字段
        Query query = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if(comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount",1);
        }else if (comment.getCommentType() == CommentType.COMMENT.getType()){
            update.inc("commentCount",1);
        }else {
            update.inc("loveCount",1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true) ;//获取更新后的最新数据
        Video modify = mongoTemplate.findAndModify(query, update, options, Video.class);
        //5、获取最新的评论数量，并返回

        if (modify.getLikeCount() != null) {
            return modify.getLikeCount();
        } else if (modify.getCommentCount() != null) {
            return modify.getCommentCount();
        } else {
            return modify.getLoveCount();
        }
    }



    //根据评论id，修改评论点赞数+1.返回更新后的点赞数
    @Override
    public Integer saveLikeComment(String commentId) {
        //构造查询条件
        Query query = Query.query(Criteria.where("id").is(commentId));
        Update update = new Update();
        //因为是点赞，所以在likeCount+1
        update.inc("likeCount", 1);
        //构造更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);
        //查询修改并返回修改后的评论对象
        Comment newComment = mongoTemplate.findAndModify(query, update, options, Comment.class);
        return newComment.getLikeCount();
    }

    //根据评论id，修改评论点赞数+1.返回更新后的点赞数
    @Override
    public Integer deleteLikeComment(String commentId) {
        //构造查询条件
        Query query = Query.query(Criteria.where("id").is(commentId));
        Update update = new Update();
        //因为是取消点赞，所以在likeCount-1
        update.inc("likeCount", -1);
        //构造更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);
        //查询修改并返回修改后的评论对象
        Comment newComment = mongoTemplate.findAndModify(query, update, options, Comment.class);
        return newComment.getLikeCount();
    }


    //根据发布者id，分页条件，查询并返回评论集合
    @Override
    public List<Comment> getCommentsByPublishUserId(Long publishUserId, int type, int page, int pagesize) {
        Query query = Query.query(
                        Criteria.where("publishUserId").is(publishUserId).and("commentType").is(type))
                .skip((page - 1) * pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        return commentList;
    }

    @Override
    public Boolean videoComment(String videoId, Long userId, CommentType commentType) {
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(videoId))
                .and("commentType").is(commentType.getType());
        Query query = Query.query(criteria);
        return mongoTemplate.exists(query,Comment.class);
    }

    @Override
    public void saveVideo(Comment comment) {
        Video video = mongoTemplate.findById(comment.getPublishId(), Video.class);
        if (video != null){
            comment.setPublishUserId(video.getUserId());
        }
        mongoTemplate.save(comment);
        Query query = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if(comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount",1);
        }else if (comment.getCommentType() == CommentType.COMMENT.getType()){
            update.inc("commentCount",1);
        }else {
            update.inc("loveCount",1);
        }

        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true) ;//获取更新后的最新数据
        Video modify = mongoTemplate.findAndModify(query, update, options, Video.class);
    }

    @Override
    public void deleteVideo(Comment comment) {
        //1、删除Comment表数据
        Criteria criteria = Criteria.where("userId").is(comment.getUserId())
                .and("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType());
        Query query = Query.query(criteria);
        mongoTemplate.remove(query,Comment.class);
        Query videoQuery = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if(comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount",-1);
        }else if (comment.getCommentType() == CommentType.COMMENT.getType()){
            update.inc("commentCount",-1);
        }else {
            update.inc("loveCount",-1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true) ;//获取更新后的最新数据
        Video modify = mongoTemplate.findAndModify(videoQuery, update, options, Video.class);
    }
}
